﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RemotingObject;
using System.Runtime.Remoting.Channels;
using System.Runtime.Serialization.Formatters;
using System.Collections;
using System.Runtime.Remoting.Channels.Tcp;
using System.Runtime.Remoting;
using System.Diagnostics;

namespace EnvCommonUtility
{
    /// <summary>
    /// 服务器端
    /// </summary>
    public class RemotingOperation4Server
    {
        #region 变量

        private RemotingObj marshal_obj;

        #endregion

        #region 构造函数

        public RemotingOperation4Server()
        {

        }

        #endregion

        #region 私有方法

        private void marshal_obj_SubscribeAtServer(string msg)
        {
            //跨线程调用
#if DEBUG
            Debug.WriteLine("Client: " + msg);
#endif
            //遍历委托列表
            Delegate[] del_list = marshal_obj.GetServerEventList();
            foreach (Delegate del in del_list)
            {
                MyDelegate d = (MyDelegate)del;
                d.BeginInvoke(
                    "服务器--" + this.ServerIP() + System.Environment.NewLine + "我是服务器，我发现一个客户端有标记行为，我要让你们全部都标记！" + System.Environment.NewLine,
                    null,
                    null);
            }
        }

        #endregion

        #region 公开的方法

        /// <summary>
        /// 开启服务器
        /// </summary>
        public void StartServer()
        {
            //设置反序列化级别
            BinaryServerFormatterSinkProvider serverProvider = new BinaryServerFormatterSinkProvider();
            BinaryClientFormatterSinkProvider clientProvider = new BinaryClientFormatterSinkProvider();
            serverProvider.TypeFilterLevel = TypeFilterLevel.Full;//支持所有类型的反序列化，级别很高

            //信道端口
            IDictionary idic = new Dictionary<string, int>();
            idic["port"] = 9438;

            //注册信道
            TcpChannel tcpchannel = new TcpChannel(idic, clientProvider, serverProvider);
            ChannelServices.RegisterChannel(tcpchannel, false);

            //服务器获取远程对象
            marshal_obj = new RemotingObj();
            ObjRef objRef = RemotingServices.Marshal(marshal_obj, "url");

            //服务器绑定客户端触发的事件
            marshal_obj.SubscribeAtServer += new MyDelegate(marshal_obj_SubscribeAtServer);
        }

        // 获取本地 IP
        public string ServerIP()
        {
            return System.Net.Dns.GetHostAddresses(System.Net.Dns.GetHostName())[0].ToString();
        }

        /// <summary>
        /// 广播消息
        /// </summary>
        /// <param name="infor">消息</param>
        public void BroadcastInformation(string infor)
        {
            marshal_obj.TriggerAtServer("服务器--" + this.ServerIP() + System.Environment.NewLine + infor + System.Environment.NewLine);
        }

        #endregion
    }
}
